//
//  FirstVCHeader.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/15.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "FirstVCHeader.h"
#import "WYADView.h"
#import "AdImgModel.h"
#import "WYPublicWeb.h"
#import "PdcDetailVC.h"
#import "NewPublishPdcModel.h"
#import "MZTimerLabel.h"
#import "PdcDetailVC.h"
#import "WYAlertView.h"
#import "AllGoosVC.h"


@interface FirstVCHeader ()
{
    
    __weak IBOutlet UILabel *timeLab1;
    __weak IBOutlet UILabel *timeLab2;
    __weak IBOutlet UILabel *timeLab3;
    //3个最新揭晓
    __weak IBOutlet UIImageView *newPic1;
    __weak IBOutlet UIImageView *newPic2;
    __weak IBOutlet UIImageView *newPic3;
    __weak IBOutlet UILabel *newLab1;
    __weak IBOutlet UILabel *newLab2;
    __weak IBOutlet UILabel *newLab3;
    __weak IBOutlet UIImageView *img1;
    __weak IBOutlet UIImageView *img2;
    __weak IBOutlet UIImageView *img3;
    __weak IBOutlet UILabel *mostNewLab;
    
    __weak IBOutlet UIView *bgView;
    //倒计时
    MZTimerLabel *timerExample1;
    MZTimerLabel *timerExample2;
    MZTimerLabel *timerExample3;
    //存放图片模型的数组
    NSMutableArray *_data;
    //存放图片链接的数组
    NSMutableArray *_pics;
    //最新揭晓
    NSMutableArray *_news;
    
    WYADView *adview;
    
    //选项按钮
    __weak IBOutlet UIButton *sBtn1;
    __weak IBOutlet UIButton *sBtn2;
    __weak IBOutlet UIButton *sBtn3;
    __weak IBOutlet UIButton *sBtn4;
    __weak IBOutlet UIButton *sBtn5;
    NSArray *_sBtns;
    __weak IBOutlet UILabel *daohangLab;
    
    //状态标志
    BOOL requestFlag1;
    BOOL requestFlag2;
    BOOL requestFlag3;

}

@property (atomic , assign) NSInteger freshCount1;

@property (atomic , assign) NSInteger freshCount2;

@property (atomic , assign) NSInteger freshCount3;
@end
@implementation FirstVCHeader


//入口函数
- (void)awakeFromNib
{
    //倒计时倒角处理
    timeLab1.layer.masksToBounds = YES;
    timeLab1.layer.cornerRadius = 2;
    timeLab2.layer.masksToBounds = YES;
    timeLab2.layer.cornerRadius = 2;
    timeLab3.layer.masksToBounds = YES;
    timeLab3.layer.cornerRadius = 2;
    //初始化数组
    _data = [NSMutableArray array];
    _pics = [NSMutableArray array];
    _news = [NSMutableArray array];
    
    //分割线
    UILabel *fenge1 = [[UILabel alloc]initWithFrame:CGRectMake(WYMWITH/3, CGRectGetHeight(bgView.frame)/2-40, 0.25, 80)];
    UILabel *fenge2 = [[UILabel alloc]initWithFrame:CGRectMake(WYMWITH/3*2, CGRectGetHeight(bgView.frame)/2-40, 0.25, 80)];
    fenge1.backgroundColor = [UIColor blackColor];
    fenge2.backgroundColor = [UIColor blackColor];
    [bgView addSubview:fenge1];
    [bgView addSubview:fenge2];
    
    
    [self addSubview:[WYPublic getFenGexian:0 :CGRectGetMaxY(mostNewLab.frame)+4 :WYMWITH :0.5]];
    [self addSubview:[WYPublic getFenGexian:0 :self.frame.size.height :WYMWITH :0.5]];
    
    _sBtns = @[sBtn1,sBtn2,sBtn3,sBtn4,sBtn5];
    
    //请求数据
    [self startRequestForData];
    [self startRequestForNews];
}
//请求数据
- (void)startRequestForData
{
    
    //临时保存数组
    NSMutableArray *arr = [NSMutableArray array];
        WYRequest *request = [[WYRequest alloc]init];
        
        [request startPostDataWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,AD_IMGS] Parameters:nil successBlock:^(NSData *responseData, NSString *responseString) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
            NSNumber *ret = dic[@"ret"];
            if (ret.intValue == 0) {
                NSArray *imgs = dic[@"data"];
                
                [_pics removeAllObjects];
                for (NSDictionary *img in imgs) {
                    AdImgModel *model = [[AdImgModel alloc]init];
                    model.img_id = img[@"id"];
                    model.img_path = img[@"img_url"];
                    //图片数组参数
                    [_pics addObject:model.img_path];
                    model.img_title = img[@"title"];
                    model.img_type = img[@"type"];
                    model.img_type_vaule = img[@"type_val"];
                    [arr addObject:model];
                }
                if (arr.count == 0) {/**********没有获取到新数据,不刷新界面************/
                    return ;
                }
//                NSLog(@" ---->p=%ld,d=%ld,r=%ld",_pics.count,_data.count,arr.count);
                if (_pics.count != _data.count) {/***********如果数据有变化******/
                    [_data removeAllObjects];
                    _data = [NSMutableArray arrayWithArray:arr];
                    
                    //创建广告图
                    adview = [[WYADView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 160) AndPics:_pics AndTitles:nil PicMode:UIViewContentModeScaleToFill];
                    adview.tag = 9999;
                    [self addSubview:adview];
                    [adview picOnClick:^(NSInteger index) {
                        AdImgModel *model = _data[index-1];
                        //根据图片类型判断跳往的界面
                        switch ([model.img_type integerValue]) {
                                
                            case 0:/************未知类型****************/
                            {
                                
                            }
                                break;
                            case 1:/*************进入网页的模式**************/
                            {
                                WYPublicWeb *webVC = [[WYPublicWeb alloc]init];
                                webVC.urlStr = model.img_type_vaule;
                                webVC.mtitle = model.img_title;
                                [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:webVC animated:YES];
                            }
                                break;
                            case 2:/************商品分类****************/
                            {
                                //获取所有商品界面单例
                                AllGoosVC *allGoodsVC = [[AllGoosVC alloc]init];
                                allGoodsVC.seach_word = model.img_title;
                                [allGoodsVC reloadVCWithSeachClassicID:model.img_type_vaule];
                                [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:allGoodsVC animated:YES];
                            }
                                break;
                            case 3:/************商品详情****************/
                            {
                                PdcDetailVC *detailVC = [[PdcDetailVC alloc]init];
                                detailVC.pdc_id = model.img_type_vaule;
                                detailVC.isSidFlag = YES;
                                [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:detailVC animated:YES];
                            }
                                break;
                            case 4:/************消息窗****************/
                            {
                                WYPublicWeb *webVC = [[WYPublicWeb alloc]init];
                                webVC.urlStr = model.img_type_vaule;
                                webVC.mtitle = model.img_title;
                                
                                //弹出对话提示
                                WYAlertView *altView = [WYAlertView showInView:self.father.view withTitle:@"温馨提示：" message:@"是否访问网页？" confirmButtonTitle:@"确定" cancelButtonTitle:@"取消"];
                                [altView handleCancel:^{
                                    
                                } handleConfirm:^{
                                    [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:webVC animated:YES];
                                }];
                                [altView show];
                            }
                                break;
                            default:
                                break;
                        }
                    }];

                }
                
            }
        } failedBlock:^{
            
        }];
        

}


//请求最新揭晓数据
- (void)startRequestForNews
{
 
    [_news removeAllObjects];
    
    NSDictionary *params = @{@"num":@"3",@"page":@"1"};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,NEW_PDC_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSArray *news = dic[@"data"];
        for (NSDictionary *pdc in news) {
            NewPublishPdcModel *model = [[NewPublishPdcModel alloc]init];
            model.pdc_new_id = pdc[@"id"];
            model.pdc_new_sid = pdc[@"sid"];
            model.pdc_new_showTimeFlag = pdc[@"q_showtime"];
            model.pdc_new_title = pdc[@"title"];
            model.pdc_new_imgUrl = pdc[@"thumb_url"];
            NSNumber *c_t = pdc[@"countdown"];
            model.pdc_new_countdown_time = [c_t integerValue];
            model.pdc_new_owner_name = pdc[@"q_username"];
            [_news addObject:model];
        }
        if(_news.count > 0){
            [self reloadNewPublishPdc];
        }
    } failedBlock:^{
        
    } needLog:NO];
}
//刷新最新推荐列表
- (void)reloadNewPublishPdc
{
    
    if (_news.count >= 3) {
        NewPublishPdcModel *model1 = _news[0];
        NewPublishPdcModel *model2 = _news[1];
        NewPublishPdcModel *model3 = _news[2];
        
        newLab1.text = model1.pdc_new_title;
        newLab2.text = model2.pdc_new_title;
        newLab3.text = model3.pdc_new_title;
        
        [newPic1 sd_setImageWithURL:[NSURL URLWithString:model1.pdc_new_imgUrl] placeholderImage:[UIImage imageNamed:@"moren"]];
        [newPic2 sd_setImageWithURL:[NSURL URLWithString:model2.pdc_new_imgUrl] placeholderImage:[UIImage imageNamed:@"moren"]];
        [newPic3 sd_setImageWithURL:[NSURL URLWithString:model3.pdc_new_imgUrl] placeholderImage:[UIImage imageNamed:@"moren"]];
        
        //model1
        if ([model1.pdc_new_showTimeFlag isEqualToString:@"N"]) {
            if([model1.pdc_new_owner_name class]!=[NSNull class])
            timeLab1.text = [WYPublic getUsefullStr:model1.pdc_new_owner_name];
            timeLab1.font = [UIFont systemFontOfSize:12];
            if (timerExample1.counting == NO) {
                timeLab1.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
            }
            img1.image = [UIImage imageNamed:@"icon_price"];
        }else if(model1.pdc_new_countdown_time == 0){
            timeLab1.text = @"正在开奖";
            timeLab1.textColor = QBB_RED_COLOR;
            img1.image = [UIImage imageNamed:@"icon_time_load"];
            [self requestForDetailLab1];
        }else{
            timeLab1.font = [UIFont systemFontOfSize:14];
            timeLab1.textColor = QBB_RED_COLOR;
            img1.image = [UIImage imageNamed:@"icon_time_load"];
            //倒计时处理
            if (timerExample1) {
                [timerExample1 pause];
                timerExample1 = nil;
            }
            timerExample1 = [[MZTimerLabel alloc] initWithLabel:timeLab1 andTimerType:MZTimerLabelTypeTimer];
            [timerExample1 setCountDownTime:model1.pdc_new_countdown_time];
            timerExample1.resetTimerAfterFinish = YES;
            timerExample1.timeFormat = @"mm:ss:SS";
            requestFlag1 = NO;
            __weak typeof (timeLab1) _weakTimeLab1;
            [timerExample1 startWithEndingBlock:^(NSTimeInterval countTime) {
                [timerExample1 pause];
                timerExample1 = nil;
                dispatch_async(dispatch_get_main_queue(), ^{
                    timeLab1.text = @"正在开奖";
                    timeLab1.textColor = QBB_RED_COLOR;
                    img1.image = [UIImage imageNamed:@"icon_time_load"];
                });
                
                
                NSInteger delay = arc4random_uniform(3);
                [self performSelector:@selector(requestForDetailLab1) withObject:nil afterDelay:delay];
//                [self requestForDetailLab1];
                
            }];
        }
        //model2
        if ([model2.pdc_new_showTimeFlag isEqualToString:@"N"]) {
            timeLab2.text = [WYPublic getUsefullStr:model2.pdc_new_owner_name];
            timeLab2.font = [UIFont systemFontOfSize:12];
            if (timerExample2.counting == NO) {
                timeLab2.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
            }
            img2.image = [UIImage imageNamed:@"icon_price"];
        }else if(model2.pdc_new_countdown_time == 0){
            timeLab2.text = @"正在开奖";
            timeLab2.textColor = QBB_RED_COLOR;
            img2.image = [UIImage imageNamed:@"icon_time_load"];
            [self requestForDetailLab2];
        }else{
            timeLab2.text = [NSString stringWithFormat:@"%ld",(unsigned long)model1.pdc_new_countdown_time];
            timeLab2.font = [UIFont systemFontOfSize:14];
            timeLab2.textColor = QBB_RED_COLOR;
            img2.image = [UIImage imageNamed:@"icon_time_load"];
            //倒计时处理
            if (timerExample2) {
                [timerExample2 pause];
                timerExample2 = nil;
            }
            timerExample2 = [[MZTimerLabel alloc] initWithLabel:timeLab2 andTimerType:MZTimerLabelTypeTimer];
            [timerExample2 setCountDownTime:model2.pdc_new_countdown_time];
            timerExample2.resetTimerAfterFinish = NO;
            timerExample2.timeFormat = @"mm:ss:SS";
            requestFlag2 = NO;
            [timerExample2 startWithEndingBlock:^(NSTimeInterval countTime) {
                [timerExample2 pause];
                timerExample2 = nil;
               
                dispatch_async(dispatch_get_main_queue(), ^{
                    timeLab2.text = @"正在开奖";
                    timeLab2.textColor = QBB_RED_COLOR;
                    img2.image = [UIImage imageNamed:@"icon_time_load"];
                });
                
                NSInteger delay = arc4random_uniform(3);
                [self performSelector:@selector(requestForDetailLab2) withObject:nil afterDelay:delay];
//                [self requestForDetailLab2];
            }];
        }
        
        //model3
        if ([model3.pdc_new_showTimeFlag isEqualToString:@"N"]) {
    
            timeLab3.text = [WYPublic getUsefullStr:model3.pdc_new_owner_name];
            timeLab3.font = [UIFont systemFontOfSize:12];
            if (timerExample3.counting == NO) {
                timeLab3.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
            }
            
            img3.image = [UIImage imageNamed:@"icon_price"];
        }else if(model3.pdc_new_countdown_time == 0){
            timeLab3.text = @"正在开奖";
            timeLab3.textColor = QBB_RED_COLOR;
            img3.image = [UIImage imageNamed:@"icon_time_load"];
            [self requestForDetailLab3];
        }else{
            timeLab3.text = [NSString stringWithFormat:@"%ld",(unsigned long)model1.pdc_new_countdown_time];
            timeLab3.font = [UIFont systemFontOfSize:14];
            timeLab3.textColor = QBB_RED_COLOR;
            img3.image = [UIImage imageNamed:@"icon_time_load"];
            //倒计时处理
            if (timerExample3) {
                [timerExample3 pause];
                timerExample3 = nil;
            }
            timerExample3 = [[MZTimerLabel alloc] initWithLabel:timeLab3 andTimerType:MZTimerLabelTypeTimer];
            [timerExample3 setCountDownTime:model3.pdc_new_countdown_time];
            timerExample3.resetTimerAfterFinish = NO;
            timerExample3.timeFormat = @"mm:ss:SS";
            requestFlag3 = NO;
            
            // 1.10
            //解决引用循环
            
//            __weak typeof (timerExample1) weakTimer1;
            // 1.10
            [timerExample3 startWithEndingBlock:^(NSTimeInterval countTime) {
                [timerExample3 pause];
                timerExample3 = nil;
                dispatch_async(dispatch_get_main_queue(), ^{
                    timeLab3.text = @"正在开奖";
                    timeLab3.textColor = QBB_RED_COLOR;
                    img3.image = [UIImage imageNamed:@"icon_time_load"];
                });
                double val = ((double)arc4random() / ARC_RANDOM_MAX);
                
                [self performSelector:@selector(requestForDetailLab3) withObject:nil afterDelay:3 * val];
            }];
        }
    }
}

//最新更多按钮
- (IBAction)morenew:(id)sender {
    [[WYMainTabBarVC shareMainTaBarVC]changeSelectedWithIndex:1];
}

//获取商品详情接口
- (void)requestForDetailLab1
{
    
    NewPublishPdcModel *model = nil;
    if (_news.count == 0) {
        return;
    }else{
        model = _news[0];
        if (model.pdc_real_time == 0) {
            timeLab1.text = @"正在开奖";
            timeLab1.textColor = QBB_RED_COLOR;
            img1.image = [UIImage imageNamed:@"icon_time_load"];
        }
    }
    if (model.pdc_new_id != nil ) {
        
        
        
        NSDictionary *params = @{@"id":model.pdc_new_id,@"get_go_total":@0};
        
        [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DETAIL_URL_NEW] Parameters:params successBlock:^(NSDictionary *dic) {
            NSDictionary *pdc = dic[@"data"];
            
            
            model.pdc_new_id = pdc[@"id"];
            model.pdc_new_sid = pdc[@"sid"];
            NSNumber *c_t = [NSNumber numberWithInteger:0];
            model.pdc_new_countdown_time = [c_t integerValue];
            model.pdc_new_owner_name = pdc[@"q_username"];
            model.pdc_new_showTimeFlag = @"N";
            
            
            requestFlag1 = YES;
            if (![model.pdc_new_owner_name isKindOfClass:[NSNull class]] && model.pdc_new_owner_name != nil){
                timeLab1.text = model.pdc_new_owner_name;
                self.freshCount1 = 0;
            }else{
                self.freshCount1 += 1;
                if (self.freshCount1 < 4){
                    NSInteger delay = arc4random_uniform(2);
                    [self performSelector:@selector(requestForDetailLab1) withObject:nil afterDelay:delay];
                    
                }
                else{
                    return;
                }
                
//                timeLab1.text = @"无法获取";
            }
                                                        
            
            if (timerExample1.counting == NO) {
                timeLab1.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
            }
            timeLab1.font = [UIFont systemFontOfSize:12];
            img1.image = [UIImage imageNamed:@"icon_price"];
            
            
            
        } failedBlock:^{
            
        } needLog:NO];
        
    }

}
//获取商品详情接口
- (void)requestForDetailLab2
{
    NewPublishPdcModel *model = nil;
    if (_news.count < 2) {
        return;
    }else{
        model = _news[1];
        if (model.pdc_real_time == 0) {
            timeLab2.text = @"正在开奖";
            timeLab2.textColor = QBB_RED_COLOR;
            img2.image = [UIImage imageNamed:@"icon_time_load"];
        }
    }
    if (model.pdc_new_id != nil && model.pdc_new_id.length != 0 ) {
        NSDictionary *params = @{@"id":model.pdc_new_id,@"get_go_total":@0};
        
        [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DETAIL_URL_NEW] Parameters:params successBlock:^(NSDictionary *dic) {
            NSDictionary *pdc = dic[@"data"];
            
            
            model.pdc_new_id = pdc[@"id"];
            model.pdc_new_sid = pdc[@"sid"];
            NSNumber *c_t = [NSNumber numberWithInteger:0];
            model.pdc_new_countdown_time = [c_t integerValue];
            model.pdc_new_owner_name = pdc[@"q_username"];
            model.pdc_new_showTimeFlag = @"N";
            
            requestFlag2 = YES;
            if (![model.pdc_new_owner_name isKindOfClass:[NSNull class]] && model.pdc_new_owner_name != nil){
                timeLab2.text = model.pdc_new_owner_name;
                self.freshCount2 = 0;
            }else{
                self.freshCount2 += 1;
                if (self.freshCount2 < 4){
                    NSInteger delay = arc4random_uniform(2);
                    [self performSelector:@selector(requestForDetailLab2) withObject:nil afterDelay:delay];
                    
                }
                else{
                    return;
                }
            }
            if (timerExample2.counting == NO) {
                timeLab2.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
            }
            timeLab2.font = [UIFont systemFontOfSize:12];
            img2.image = [UIImage imageNamed:@"icon_price"];
            
            
            
        } failedBlock:^{
            
        } needLog:NO];
        
    }
    
}
//获取商品详情接口
- (void)requestForDetailLab3
{
    NewPublishPdcModel *model = nil;
    if (_news.count < 3) {
        return;
    }else{
        model = _news[2];
        if (model.pdc_real_time == 0) {
            timeLab3.text = @"正在开奖";
            timeLab3.textColor = QBB_RED_COLOR;
            img3.image = [UIImage imageNamed:@"icon_time_load"];
        }
    }
    if (model.pdc_new_id != nil ) {
        
        NSDictionary *params = @{@"id":model.pdc_new_id,@"get_go_total":@0};
        
        [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DETAIL_URL_NEW] Parameters:params successBlock:^(NSDictionary *dic) {
            NSDictionary *pdc = dic[@"data"];
            if (model.pdc_new_id == pdc[@"id"]){
                
            }
            model.pdc_new_id = pdc[@"id"];
            model.pdc_new_sid = pdc[@"sid"];
            NSNumber *c_t = [NSNumber numberWithInteger:0];
            model.pdc_new_countdown_time = [c_t integerValue];
            model.pdc_new_owner_name = pdc[@"q_username"];
            model.pdc_new_showTimeFlag = @"N";
            
            if (timerExample3.counting == NO) {
                timeLab3.text = @"正在开奖";
                timeLab3.textColor = QBB_RED_COLOR;
                img3.image = [UIImage imageNamed:@"icon_time_load"];
            }

            requestFlag3 = YES;
            if (![model.pdc_new_owner_name isKindOfClass:[NSNull class]] && model.pdc_new_owner_name != nil){
                timeLab3.text = model.pdc_new_owner_name;
                self.freshCount3 = 0;
            }else{
                self.freshCount3 += 1;
                if (self.freshCount3 < 4){
                    NSInteger delay = arc4random_uniform(2);
                    [self performSelector:@selector(requestForDetailLab3) withObject:nil afterDelay:delay];
                    
                }
                else{
                    return;
                }
//                [self requestForDetailLab3];
//                timeLab3.text = @"无法获取";
            }
            if (timerExample3.counting == NO) {
                timeLab3.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"db_blu_color"]];
            }
            timeLab3.font = [UIFont systemFontOfSize:12];
            img3.image = [UIImage imageNamed:@"icon_price"];
            
        } failedBlock:^{
            
        } needLog:NO];
    
    }
    
}
//最新揭晓商品
- (IBAction)pdcOnClick:(id)sender {
    self.father.firstFlag = NO;
    UIButton *btn = (UIButton *)sender;
    if(_news.count> 0){
        NewPublishPdcModel *model = _news[btn.tag-1];
        //跳往商品详情
        PdcDetailVC *detailVC = [[PdcDetailVC alloc]init];
        detailVC.pdc_id = model.pdc_new_id;
        [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:detailVC animated:YES];
    }
}

//选项按钮
- (IBAction)selectOnClick:(UIButton *)sender {
    //筛选条件
    NSArray *types = @[@"-10", @"20", @"-30", @"-40", @"40"];
    for (UIButton *btn in _sBtns) {
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    [sender setTitleColor:QBB_RED_COLOR forState:UIControlStateNormal];
    [UIView animateWithDuration:0.2 animations:^{
        daohangLab.center = CGPointMake(sender.center.x, daohangLab.center.y);
    }];
    self.isFilterFresh = YES;
    [self.father changeupdateWithId:types[sender.tag%10]];
}

@end
